<template>
  <div v-if="visible">
    <el-dialog :visible.sync="visible"
               :title="!dataForm.id ? `${$t('add')}用户` : `${$t('update')}用户`"
               class="user-dialog add-or-updata"
               width="35%"
               :append-to-body="true"
               :before-close="closeDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form :model="dataForm"
               v-loading="dataListLoading"
               ref="dataForm"
               label-position="left"
               @keyup.enter.native="dataFormSubmitHandle()"
               label-width="80px">
        <el-form-item prop="username"
                      label="账号"
                      :rules="validatorRule(validateUsername)">
          <el-input v-model.trim="dataForm.username"
                    class="width-100"
                    :disabled="dataForm.id !== ''"
                    :placeholder="$t('user.username')"></el-input>
        </el-form-item>
        <el-form-item prop="realName"
                      label="姓名"
                      :rules="stringRule(true,1,20)">
          <el-input v-model.trim="dataForm.realName"
                    :placeholder="$t('user.realName')"></el-input>
        </el-form-item>
        <el-form-item prop="phone"
                      label="手机号"
                      :rules="mobileRule()">
          <el-input v-model.trim="dataForm.phone"
                    placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item prop="email"
                      label="邮箱"
                      :rules="emailRule(false)">
          <el-input v-model.trim="dataForm.email"
                    :placeholder="$t('user.email')"></el-input>
        </el-form-item>
        <el-form-item class="dept-list"
                      :rules="required()"
                      label="部门"
                      prop="deptName">
          <el-popover v-model.trim="deptListVisible"
                      ref="deptListPopover"
                      placement="bottom-start"
                      trigger="click">
            <el-tree :data="deptList"
                     :props="{ label: 'name', children: 'children' }"
                     node-key="id"
                     ref="deptListTree"
                     :highlight-current="true"
                     :expand-on-click-node="false"
                     accordion
                     @current-change="deptListTreeCurrentChangeHandle">
            </el-tree>
          </el-popover>
          <el-input v-model.trim="dataForm.deptName"
                    v-popover:deptListPopover
                    :readonly="true"
                    :placeholder="$t('user.deptName')"></el-input>
        </el-form-item>
        <el-form-item prop="positionId"
                      label="职位"
                      :rules="required()">
          <el-select v-model="dataForm.positionId"
                     class="width-100"
                     filterable
                     placeholder="请选择">
            <el-option v-for="item in jobOptions"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="gender"
                      label="性别"
                      :rules="required()">
          <el-radio-group v-model="dataForm.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>

        </el-form-item>
        <el-form-item prop="status"
                      label="状态"
                      :rules="required()">
          <el-switch v-model="dataForm.status"
                     :active-value="1"
                     :inactive-value="0"
                     active-color="#13ce66"
                     inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item prop="remarks"
                      label="备注"
                      show-word-limit
                      :rules="stringRule(false,0,50)">
          <el-input v-model.trim="dataForm.remarks"
                    type="textarea"
                    :autosize="{ minRows: 3, maxRows: 4}"
                    maxlength="50"
                    show-word-limit
                    placeholder="备注"></el-input>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button type="primary"
                   :loading="isRequest"
                   @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
        <el-button @click="closeDialog()">{{ $t('cancel') }}</el-button>
      </template>
      <div style="display: none;color: red">说明:新增用户默认密码为kaijin2022</div>
    </el-dialog>
  </div>
</template>

<script>
import formValidate from '@/mixins/form-validate'
import mixinViewModule from '@/mixins/view-module'
import debounce from 'lodash/debounce'
import axios from 'axios'
// import { mapState } from 'vuex'
export default {
  mixins: [mixinViewModule, formValidate],
  data () {
    return {
      mixinViewModuleOptions: {
        deleteImgURL: '/tb/file/deleteImage',
        addURL: 'system/sysUser', // 添加或修改的接口
        updateURL: 'system/sysUser', // 添加或修改的接口
        getDeptURL: '/system/sysUser/getDeptInUser', // 获取部门列表的接口
        getDistrictInUserURL: '/system/sysUser/getDistrictInUser', // 查询地区
        getJobListURL: '/system/sysPosition/getPositionList', // 获取职业列表
        getDataInfoURL: '' // 获取数据详情的接口
      },
      dataListLoading: false,
      isRequest: false,
      visible: false,
      deptList: [],
      jobOptions: [],
      deptListVisible: false,
      dataForm: {
        id: '',
        positionId: '',
        username: '',
        deptId: '0',
        deptName: '',
        realName: '',
        email: '',
        phone: '',
        remarks: '',
        gender: 0,
        status: 1
      }
    }
  },
  components: {
  },
  methods: {
    // 用户校验
    validateUsername (rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else if (value.length > 10) {
        callback(new Error('请输入4-10位字母,数字做为用户名'))
      } else {
        let pPattern = /^[a-zA-Z0-9]{4,10}$/g
        if (pPattern.test(value)) {
          callback()
        } else {
          callback(new Error('请输入4-10位字母,数字做为用户名'))
        }
      }
    },
    closeDialog () {
      this.dataForm.id = ''
      this.dataForm.positionId = ''
      this.dataForm.username = ''
      this.dataForm.deptId = ''
      this.dataForm.deptName = ''
      this.dataForm.realName = ''
      this.dataForm.email = ''
      this.dataForm.phone = ''
      this.dataForm.remarks = ''
      this.dataForm.gender = 0
      this.dataForm.status = 1
      this.deptListVisible = false
      this.visible = false
      this.isRequest = false
      this.$emit('callBack')
    },
    init (data) {
      console.log(data)
      if (data) {
        this.dataForm = data
        // this.$refs.deptListTree.setCurrentKey(this.dataForm.deptId)
      }
      this.visible = true
      let that = this
      this.jobOptions = []
      this.deptList = []
      axios.all([this.getDeptList(), this.getJobList()])
        .then(axios.spread(function (dept, jobs) {
          // 两个请求现在都执行完成
          if (dept.code !== 0 || jobs.code) {
            return false
          }
          // 添加部门列表
          that.deptList.push(...dept.data)
          // 添加职业列表
          that.jobOptions.splice(0, that.jobOptions.length, ...jobs.data)
        }))
    },
    // 获取职业列表
    getJobList () {
      return this.getDataList({ url: this.mixinViewModuleOptions.getJobListURL, paramData: {} })
    },
    // 获取部门列表
    getDeptList () {
      return this.getDataList({
        paramData: {},
        url: this.mixinViewModuleOptions.getDeptURL
      })
    },
    // 获取地区列表
    getDistrictInUser () {
      return this.getDataList({ url: this.mixinViewModuleOptions.getDistrictInUserURL })
    },
    // 所属部门树, 选中
    deptListTreeCurrentChangeHandle (data, node) {
      this.dataForm = Object.assign({}, this.dataForm, {
        deptId: data.id,
        deptName: data.name
      })
      this.deptListVisible = false
    },
    // 表单提交s
    dataFormSubmitHandle: debounce(function () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.isRequest = true
          const url = this.dataForm.id ? this.mixinViewModuleOptions.updateURL : this.mixinViewModuleOptions.addURL
          this.addOrUpdateItem({ url }).then(res => {
            if (res.code !== 0) {
              this.isRequest = false
              return
            }
            this.closeDialog()
          })
        }
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss" scoped>
.user-dialog {
  background: rgba(0, 0, 0, 0.5);
}
.mod-sys__user {
  .dept-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}
</style>
